<template>
  <div class="mapContent">
    <div id="map" ref="threeDBox"></div>
  </div>
</template>

<script>
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import { CSS2DRenderer } from 'three/examples/jsm/renderers/CSS2DRenderer.js'
// import * as d3 from 'd3'
import { borderLine } from '@/utils/line'
import { shapeMesh } from '@/utils/shapeMesh'
import { tag } from '@/utils/tag'
import { cityPointMesh } from '@/utils/cityPointMesh';
import { ConeMesh } from '@/utils/ConeMesh';
export default {
  name: 'MapData',
  data() {
    return {
      scene:null,
      loader:null,
      mapGroup:null,
      lineGroup:null,
      lineGroup2:null,
      meshGroup:null,
      camera:null,
      renderer:null,
      controls:null,
      label:null,
      chooseMesh:null,
      labelRenderer:null,
      icon:null,
      iconS:1,
      cone:null,
      loaderData:[],
      data2:[
        {
          "name": "北京市",
          "value": "35371.28"
        },
        {
          "name": "天津市",
          "value": "14104.28"
        },
        {
          "name": "河北省",
          "value": "35104.52"
        },
        {
          "name": "山西省",
          "value": "17026.68"
        },
        {
          "name": "内蒙古自治区",
          "value": "17212.53"
        },
        {
          "name": "辽宁省",
          "value": "24909.45"
        },
        {
          "name": "吉林省",
          "value": "11726.82"
        },
        {
          "name": "黑龙江省",
          "value": "13612.68"
        },
        {
          "name": "上海市",
          "value": "38155.32"
        },
        {
          "name": "江苏省",
          "value": "99631.52"
        },
        {
          "name": "浙江省",
          "value": "62351.74"
        },
        {
          "name": "安徽省",
          "value": "37113.98"
        },
        {
          "name": "福建省",
          "value": "42395"
        },
        {
          "name": "江西省",
          "value": "24757.5"
        },
        {
          "name": "山东省",
          "value": "71067.53"
        },
        {
          "name": "河南省",
          "value": "54259.2"
        },
        {
          "name": "湖北省",
          "value": "45828.31"
        },
        {
          "name": "湖南省",
          "value": "39752.12"
        },
        {
          "name": "广东省",
          "value": "107671.07"
        },
        {
          "name": "广西壮族自治区",
          "value": "21237.14"
        },
        {
          "name": "海南省",
          "value": "5308.93"
        },
        {
          "name": "重庆市",
          "value": "23605.77"
        },
        {
          "name": "四川省",
          "value": "46615.82"
        },
        {
          "name": "贵州省",
          "value": "16769.34"
        },
        {
          "name": "云南省",
          "value": "23223.75"
        },
        {
          "name": "西藏自治区",
          "value": "1697.82"
        },
        {
          "name": "陕西省",
          "value": "25793.17"
        },
        {
          "name": "甘肃省",
          "value": "8718.3"
        },
        {
          "name": "青海省",
          "value": "2965.95"
        },
        {
          "name": "宁夏回族自治区",
          "value": "3748.48"
        },
        {
          "name": "新疆维吾尔自治区",
          "value": "13597.11"
        },
        {
          "name": "台湾省",
          "value": "42100"
        },
        {
          "name": "香港特别行政区",
          "value": "25622"
        },
        {
          "name": "澳门特别行政区",
          "value": "3609"
        }
      ]
    }
  },
  props:{
    passUserCount:{
      default:0
    },
    studyCount:{
      default:0
    },
  },
  mounted() {
    this.getNewMap()
    // this.renderer.domElement.addEventListener('mousemove',this.choose)
    this.renderer.domElement.addEventListener('click',this.choose)
  },
  methods:{
    getNewMap() {
      this.scene = new THREE.Scene()

      // const axesHelper = new THREE.AxesHelper(5);
      // this.scene.add(axesHelper);
      
      const ambientLight = new THREE.AmbientLight(0xd4e7fd, 4)
      this.scene.add(ambientLight)

      this.loader = new THREE.FileLoader()

      this.loader.setResponseType('json')

      this.mapGroup = new THREE.Group()
      this.scene.add(this.mapGroup)

      this.lineGroup = new THREE.Group()
      this.mapGroup.add(this.lineGroup)

      this.lineGroup2 = this.lineGroup.clone()
      this.mapGroup.add(this.lineGroup2)


      this.meshGroup = new THREE.Group()
      this.mapGroup.add(this.meshGroup)

      this.lineGroup.position.z = 1+0.001
      this.lineGroup2.position.z = -0.001
      // this.loader.load('./gdp.json',(data2)=>{
        
      //   let gdpObj = {}
      //   let color = new THREE.Color(0x257dcd);
      //   data2.arr.forEach((item)=>{
      //     let gdp = item.value
      //     gdpObj[item.name] = gdp
      //   })
      this.loader.load('./china.json',(data)=>{
        let gdpObj = {}
        let color = new THREE.Color(0x257dcd);
        this.data2.forEach((item)=>{
          let gdp = item.value
          gdpObj[item.name] = gdp
        })

        this.loaderData = data.features
        data.features.forEach((area)=>{
          // 添加水波图
          this.icon = cityPointMesh(2.0, area.properties.center[0]-104, area.properties.center[1]-35, area.properties.name);
          this.icon.position.z = 1.7
          this.icon.visible = false
          this.scene.add(this.icon)

          // 添加光锥
          this.cone = ConeMesh(0.5, area.properties.center[0]-104, area.properties.center[1]-35, area.properties.name)
          this.cone.position.z = 2
          this.cone.visible = false
          this.scene.add(this.cone)

          if (area.geometry.type === "Polygon") {
            // 把"Polygon"和"MultiPolygon"的geometry.coordinates数据结构处理为一致
            area.geometry.coordinates = [area.geometry.coordinates];
          }
          this.lineGroup.add(borderLine(area.geometry.coordinates))
          let mesh = shapeMesh(area.geometry.coordinates)
          mesh.name = area.properties.name
          this.meshGroup.add(mesh)
          let newGdp = gdpObj[mesh.name]
          // let color = color1.clone().lerp(color2.clone(), newGdp / gdpMax)
          mesh.material.color.copy(color)
          mesh.gdp = newGdp
          mesh.longitude = area.properties.center
          mesh.color = color
        })
      })
      // })

      const width = 930
      const height = 587
      this.camera = new THREE.PerspectiveCamera(
        75,
        width / height,
        0.1,
        1000
      )
      this.camera.position.set(0, 0, 30);
      this.camera.lookAt(0, 0, 0);
      
      this.labelRenderer = new CSS2DRenderer()
      this.labelRenderer.domElement.style.position = 'absolute'
      this.labelRenderer.domElement.style.top = '0px'
      this.labelRenderer.domElement.style.pointerEvents = 'none'
      this.labelRenderer.setSize(width, height)
      document.getElementById('map').appendChild(this.labelRenderer.domElement)

      this.renderer = new THREE.WebGLRenderer({
        alpha: true,
        antialias: true, //开启锯齿
      });
      this.renderer.setSize(width, height)
      document.getElementById('map').appendChild(this.renderer.domElement)
      
      this.render();
      
      this.controls = new OrbitControls(this.camera, this.renderer.domElement)
      this.controls.target.set(0, 0, 0);
      this.controls.minDistance = 1;
      this.controls.maxDistance = 30;
      this.controls.minPolarAngle = 1;
      this.controls.maxPolarAngle = 2.5;
      this.controls.update()

      this.label = tag()
      this.scene.add(this.label)
    },
    render() {
      this.scene.children.forEach((item)=>{
        if(item.isMesh) {
          if(item.geometry.type == 'ConeGeometry') {
            item.rotateZ(0.04)
          }
          if(item.geometry.type == 'PlaneGeometry') {
            this.iconS += 0.0005
            item.scale.set(this.iconS, this.iconS, this.iconS)
            if (this.iconS <= 1.5) {
              item.material.opacity = (this.iconS-1) * 2;//2等于1/(1.5-1.0)，保证透明度在0~1之间变化
            } else if (this.iconS > 1.5 && this.iconS <= 2) {
              item.material.opacity =  1 - (this.iconS - 1.5)*2;//2等于1/(2.0-1.5) mesh缩放2倍对应0 缩放1.5被对应1
            } else {
              this.iconS = 1.0;
            }
          }
        }
      })
      this.labelRenderer.render(this.scene, this.camera);
      this.renderer.render(this.scene, this.camera); //执行渲染操作
      requestAnimationFrame(this.render); //请求再次执行渲染函数render，渲染下一帧
    },
    choose(event) {
      if(!event){
        if(this.chooseMesh.material){
          this.chooseMesh.material.color.set(0x257dcd);//选中改变颜色          
        }
        // console.log(this.chooseMesh);
        // console.log(this.scene);
        // this.scene.children.forEach((item)=>{
        //   if(item.isMesh) {
        //     console.log(item.geometry.type);
        //     // if(item.geometry.type == 'ExtrudeGeometry'){
        //     //   console.log(item);
        //     //   item.color.set(0x257dcd);//选中改变颜色
        //     // }
        //   }
        // })
        this.$emit('changeIndex',0)
        this.chooseMesh = null;
        this.label.element.style.visibility = 'hidden';
        this.scene.children.forEach((item)=>{
          if(item.isMesh) {
            item.visible = false
          }
        })
        return
      }
      if(this.chooseMesh) {
        this.chooseMesh.material.color.copy(this.chooseMesh.color);
      }else {
        this.label.element.style.visibility = 'hidden';
      }
      let left = 512
      let top = 123
      let Sx = event.clientX-left; //鼠标单击位置横坐标
      let Sy = event.clientY-top; //鼠标单击位置纵坐标
      //屏幕坐标转WebGL标准设备坐标
      let x = (Sx / 930) * 2 - 1; //WebGL标准设备横坐标
      let y = -(Sy / 587) * 2 + 1; //WebGL标准设备纵坐标

      const raycaster = new THREE.Raycaster();
      raycaster.setFromCamera(new THREE.Vector2(x, y), this.camera);

      const intersects = raycaster.intersectObjects(this.meshGroup.children);
      
      if (intersects.length > 0) {
        this.chooseMesh = intersects[0].object;
        this.chooseMesh.material.color.set(0x00ffff);//选中改变颜色
        this.label.position.set(this.chooseMesh.longitude[0]-104, this.chooseMesh.longitude[1]-35, 0);
        // this.$nextTick(()=>{
        //   this.label.element.innerHTML = `地区:${this.chooseMesh.name}<br/>通过人数:${this.passUserCount}<br/>
        //   参学人数:${this.studyCount}`;          
        // })
        this.label.element.style.visibility = 'visible';
        this.scene.children.forEach((item)=>{
          if(item.isMesh) {
            if(item.geometry.type == 'ConeGeometry') {
              if(item.material.name == this.chooseMesh.name) {
                item.visible = true
              }else {
                item.visible = false
              }
            }
            if(item.geometry.type == 'PlaneGeometry') {
              if(item.material.name == this.chooseMesh.name) {
                item.visible = true
              }else {
                item.visible = false
              }
            }
          }
        })
        this.data2.forEach((item,index)=>{
          if(item.name == this.chooseMesh.name) {
            this.$emit('changeIndex',index)
            console.log('=>',index)
            this.$nextTick(()=>{
              this.label.element.innerHTML = `地区:${this.chooseMesh.name}<br/>通过人数:${this.passUserCount}<br/>
              参学人数:${this.studyCount}`;          
            })
          }
        }) 
        console.log('this.chooseMesh',this.chooseMesh);
      } else {
        this.$emit('changeIndex',0)
        this.chooseMesh = null;
        this.label.element.style.visibility = 'hidden';
        this.scene.children.forEach((item)=>{
          if(item.isMesh) {
            item.visible = false
          }
        })
      }
    }
  }
}
</script>
<style scoped>
.mapContent {
  width: 58.125rem;
  height: 36.6875rem;
  position: relative;
}
</style>
